﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Ruandao.MiniFace
{
    public class ExpressionItem : ValueItem
    {
        public string Expression { get; private set; }

        public ExpressionItem(Template template, string expression)
            : base(template)
        {
            this.Expression = expression;
        }
        public override object GetValue( TemplateContext templateContext)
        {
            return PythonEngine.GetEngine().Execute(this.Expression, templateContext.PythonScope);
        }

        public override void Render( TemplateContext templateContext, TextWriter writer)
        {

            try
            {
                object o = this.GetValue(templateContext) ;
                writer.Write(o==null ? "" : o.ToString());
            }
            catch (Exception ex)
            {
                GetExceptionMessage(ex);
            }
        }

        [Conditional("DEBUG")]
        private void GetExceptionMessage(Exception ex)
        {
            ex = new Exception("此表达式不能被识别：\"" + this.Expression);
            throw ex;
        }
    }
}
